package day7;

import day5.Person;

import java.lang.reflect.Field;

//a.通过反射定义一个方法可以实现修改任意对象的属性值
//    通过反射定义一个方法可以实现获取任意对象的属性值
//    如：setProperty(对象，属性名,新的属性值)    设置
//        getProperty(对象，属性名)  获取
public class Work1 {
    public static void main(String[] args) {
        Person p=new Person("aaa",18);
        setProperty(p,"name","张三");
        System.out.println(getProperty(p,"name"));
    }
    public static void setProperty(Object o,String name,Object value){
        try {
            Class c=o.getClass();
            Field f=c.getDeclaredField(name);
            f.setAccessible(true);
            f.set(o,value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Object getProperty(Object o,String name){
        Object result= null;
        try {
            Class c=o.getClass();
            Field f=c.getDeclaredField(name);
            f.setAccessible(true);
            result = f.get(o);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
